import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

const state = {
    username: '',
    token: null,
    isLogin: false,
    msg:''
}
const getters = {
}
const mutations = {
    logout(state) {
        state.username = ''
        state.token = null
        state.isLogin = false
    }, // 登出
    setUsername(state, payload){
        state.username = payload
    },
    setToken(state, payload){
        state.token = payload
    },
    clearToken(state) {
        state.token = null
    },
    SetLoginState(state,payload){
        state.isLogin = payload
    }
}
const actions = {
    login(state, payload) {
       // let  {username, password} = payload
        console.log(payload,'payload')
        axios.post('https://www.fastmock.site/mock/0fcda8fd40622d9d49aa173cc1fa5bd8/jumei/login')
            .then(res =>{
                console.log(res.data)
                console.log(res.data.data.token)
                state.token = res.data.data.token
                state.username = res.data.data.username
                if (res.data.error_code === 0) {
                    state.msg = '登陆成功'
                } else {
                    state.msg = '登陆失败'
                }
            })
            .catch(err => {
                console.log(err)
                state.msg = '登陆失败'
            })
    }, // 登陆
    register(state, payload) {
        let  [username, password] = payload
        this.axios.post('https://www.fastmock.site/mock/0fcda8fd40622d9d49aa173cc1fa5bd8/jumei/register',{
            username,
            password
        })
            .then(res =>{
                if (res.data.error_code === '0') {
                    state.msg = '注册成功，请登陆'
                } else {
                    state.msg = '注册失败'
                }
            })
            .catch(err => {
                console.log(err)
                state.msg = '注册失败'
            })
    } // 注册
}

export default {
    namespaced: true, // 开启命名空间
    state,
    getters,
    mutations,
    actions
}
